package com.junjun.ssm.controller;

import com.alibaba.fastjson2.JSONObject;
import com.junjun.ssm.dao.ErrorOrderDao;
import com.junjun.ssm.dao.OrderDao;
import com.junjun.ssm.dto.OrderDto;
import com.junjun.ssm.entity.ErrorOrder;
import com.junjun.ssm.entity.OrderEntity;
import com.junjun.ssm.entity.UserEntity;
import com.junjun.ssm.util.ConvertBeanUtil;
import com.junjun.ssm.util.Verifier;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    OrderDao orderDao;


    @Autowired
    ErrorOrderDao errorOrderDao;

  /*  @PostMapping("addOrder")
    public void addOrder(@RequestBody OrderEntity orderEntity) {

        this.userid=orderEntity.getUserId();
        //生成时间
        LocalDateTime localDateTime = LocalDateTime.now();
        orderEntity.setPurchaseTime(String.valueOf(localDateTime));
        orderEntity.setPurchaseNum(1);
        String key = String.valueOf(orderEntity.getUserId());
        redisTemplate.opsForList().leftPush(key, orderEntity);
    }*/


  /*  @Scheduled(fixedDelay = 5000) //定时调度
    public void addOrderEntity() throws InterruptedException {

        String key = String.valueOf(userid);
        //数据取出redis


        while (true) {
            Thread.sleep(3000);
            LinkedHashMap order = (LinkedHashMap) redisTemplate.opsForList().rightPop(key);
            if (order == null) {

            } else {

                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setPurchaseNum((Integer) order.get("purchaseNum"));
                orderEntity.setUserId((Integer) order.get("userId"));
                orderEntity.setMovieName((String) order.get("movieName"));
                orderEntity.setMovieNumber((String) order.get("movieNumber"));
                orderEntity.setUserName((String) order.get("userName"));
                orderEntity.setPurchaseTime((String) order.get("purchaseTime"));
                orderDao.save(orderEntity);
            }

        }

    }*/

    @RabbitListener(queues = "queueOne")
    public void messageToMeiTuan(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, OrderDto orderDto) throws Exception {
        //   int num = (int) (Math.random() * 10+1);

        LocalDateTime localDate = LocalDateTime.now();
        OrderEntity orderEntity = ConvertBeanUtil.copy(orderDto, OrderEntity.class);
        orderEntity.setPurchaseTime(String.valueOf(localDate));
        orderEntity.setPayment(0);
        orderDao.save(orderEntity);
        channel.basicAck(tag, false); //tag -关联数据，bl-不批量确认

        //   channel.basicNack(tag, false,false);//b1 false  不放回队列


    }

    @RabbitListener(queues = "deadQueue")
    public void DeadMessageToMeiTuan(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, OrderDto orderDto) throws IOException, InterruptedException {


        ErrorOrder orderEntity = ConvertBeanUtil.copy(orderDto, ErrorOrder.class);

        errorOrderDao.save(orderEntity);
        System.out.println("异常订单");

        channel.basicAck(tag, false); //tag -关联数据，bl-不批量确认


    }

    @PostMapping("orderUser")
    public OrderEntity orderUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        String result = Verifier.verifierJwt(token);
        UserEntity user = JSONObject.parseObject(result, UserEntity.class);
        System.out.println(user.getUserID() + "id");
        OrderEntity orderEntity = null;
        while (true) {

            if (orderEntity != null) {

                return orderEntity;
            } else {
                orderEntity = orderDao.findByUserId(user.getUserID(), 0);
            }


        }
    }

    @PostMapping("removeMovie")
    public void removeMovie(Long id) {

        orderDao.deleteById(id);


    }


    @PostMapping("deterOrder")
    public OrderEntity determine(@RequestBody OrderEntity orderEntity) {

OrderEntity orderEntity1=orderDao.findByOrderId(orderEntity.getOrderId());

        return orderEntity1;

    }

    @PostMapping("queryAll")
    public List<OrderEntity> queryAll() {


        return orderDao.queryAll();

    }

    @PostMapping("unpaidOrder")
    public List<OrderEntity> queryAllUnpaidOrder(HttpServletRequest request) {
        String token = request.getHeader("token");
        String result = Verifier.verifierJwt(token);
        UserEntity user = JSONObject.parseObject(result, UserEntity.class);

        return orderDao.queryAllUnpaidOrder(user.getUserID(), 0);

    }

}

